package com.liuwa.common.bean;

import com.alibaba.fastjson.annotation.JSONField;
import com.liuwa.common.utils.StringUtils;
import com.liuwa.common.utils.sql.SqlUtil;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Liuwa
 * @Date: 2022/5/15 12:55
 */
public abstract class SortedPageQuery extends BasePageQuery {

    /**
     * 排序字段
     */
    @ApiModelProperty(value = "排序字段", name = "sort_field")
    protected String sortField;

    /**
     * 排序方向(DESC, ASC)
     */
    @ApiModelProperty(value = "排序方向(DESC, ASC)", name = "sort_direction")
    protected String sortDirection;

    /**
     * 排序（保留字段）
     */
    @ApiModelProperty(value = "排序（保留字段）", name = "order_by", hidden = true)
    protected String orderBy;


    public String getSortField() {
        return sortField;
    }

    public void setSortField(String sortField) {
        this.sortField = sortField;
    }

    public String getSortDirection() {
        return sortDirection;
    }

    public void setSortDirection(String sortDirection) {
        this.sortDirection = sortDirection;
    }

    /**
     * 兼容旧方式
     * @param orderByColumn
     */
    public void setOrderByColumn(String orderByColumn){
        if(StringUtils.isNotEmpty(orderByColumn)){
            this.sortField = StringUtils.toUnderScoreCase(orderByColumn);
        }

    }

    /**
     * 兼容旧方式
     * @param isAsc
     */
    public void setIsAsc(String isAsc){
        if (StringUtils.isNotEmpty(isAsc))
        {
            // 兼容前端排序类型
            if ("descending".equals(isAsc))
            {
                this.sortDirection = "desc";
            }
            else{
                this.sortDirection = "asc";
            }
        }
    }

    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    /**
     * 默认排序
     * @return
     */
    public abstract Sort defaultSort();

    /**
     * 获取 排序字符串
     * @return
     */
    public String getOrderByString(){
        Sort sort = getSort();
        if(sort== null){
            return null;
        }
        return  sort.get().map(order-> {return order.getProperty() + " " + order.getDirection().toString().toLowerCase();}).collect(Collectors.joining(","));

    }

    /**
     * 获取排序
     * @return
     */
    @JSONField(serialize = false)
    public Sort getSort(){
        if(StringUtils.isEmpty(orderBy)){
            if(StringUtils.isNotEmpty(sortField)){
                orderBy = sortField + " " + (StringUtils.isEmpty(sortDirection) ? Sort.Direction.ASC.toString() : sortDirection);
            }
        }
        if(StringUtils.isEmpty(orderBy)){
            return defaultSort();
        }

        orderBy = SqlUtil.escapeOrderBySql(orderBy);
        List<Sort.Order> sortOrders = new ArrayList<Sort.Order>();
        String[] parts = orderBy.split(",");
        for(String part : parts){
            part = part.trim().replaceAll("\\s+", " ");
            if("".equals(part)){
                continue;
            }
            String[] arr = part.split(" ", 2);
            String field = arr[0];
            String direction = arr.length == 2 ? arr[1] : Sort.Direction.ASC.toString();
            Sort.Direction sortDirection = Sort.Direction.fromString(direction);
            if(sortDirection.isAscending()){
                sortOrders.add(Sort.Order.asc(field));
            }
            else{
                sortOrders.add(Sort.Order.desc(field));
            }
        }
        if(sortOrders.size() != 0){
            return Sort.by(sortOrders);
        }

        return defaultSort();
    }
}